package com.danikula.videocache.file

import android.content.Context
import java.io.File
import java.io.IOException

object CacheDirUtils {

    // 获取视频缓存目录
    fun getVideoCacheDir(context: Context) = File(context.externalCacheDir, "video-cache")

    fun cleanVideoCacheDir(context: Context) = cleanDirectory(getVideoCacheDir(context))

    private fun cleanDirectory(file: File) {
        if (!file.exists()) {
            return
        }
        file.listFiles()?.forEach {
            delete(it)
        }
    }

    @Throws(IOException::class)
    private fun delete(file: File) {
        if (file.isFile && file.exists()) {
            deleteOrThrow(file)
        } else {
            cleanDirectory(file)
            deleteOrThrow(file)
        }
    }

    @Throws(IOException::class)
    private fun deleteOrThrow(file: File) {
        if (file.exists()) {
            val isDeleted = file.delete()
            if (!isDeleted) {
                throw IOException(String.format("File %s can't be deleted", file.absolutePath))
            }
        }
    }
}